package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mff
 * @date 2022/6/9 9:14
 * @mood happy
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;



//    新增菜品、套餐分类
    @PostMapping
    public R<String> saveCategory(@RequestBody Category category){
        boolean result = categoryService.save(category);
        if (result){
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

//    分页查询
    @GetMapping("/page")
    public R<Map<String,Object>> page(int page,int pageSize){
//        构造分页器
        Page page1 = new Page(page, pageSize);
//        构造查询条件
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        排序规则
        categoryLambdaQueryWrapper.orderByDesc(Category::getSort);
        categoryLambdaQueryWrapper.orderByDesc(Category::getCreateTime);
//        执行分页查询
        categoryService.page(page1, categoryLambdaQueryWrapper);

        List records = page1.getRecords();
        long total = page1.getTotal();

        Map data = new HashMap();
        data.put("records", records);
        data.put("total", total);

        return R.success(data);
    }


//    删除分类接口（多表）删除时要考虑该菜品、套餐下是否有具体的菜
    @DeleteMapping
    public R<String> delete(Long id){
        return categoryService.remove(id);
    }

//    修改套餐接口
    @PutMapping
    public R<String> updateCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

//  新增菜品功能
//    接口1：查询菜品分类列表
    @GetMapping("/list")
    public R<List<Category>> dishList(Category category){ //会将type封装到category
        Integer type = category.getType();
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(type != null, Category::getType, type);
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);
        return R.success(list);
    }




}
